from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from schemas.consultation_schemas import ConsultationCreate, ConsultationUpdate, ConsultationResponse
from services.consultation_service import (
    get_consultation,
    get_consultations,
    create_consultation,
    update_consultation,
    delete_consultation,
    get_consultations_by_patient, get_consultations_by_doctor
)
from services.auth_service import require_user
from models.user_models import UserType,Patient



router=APIRouter()

@router.get("/consultations", response_model=list[ConsultationResponse])
def read_consultations(skip: int = 0, limit: int = 100, db: Session = Depends(get_db),
                      user=Depends(require_user(UserType.ADMIN))):     #查询所有只允许管理员
    consultations = get_consultations(db, skip=skip, limit=limit)
    return consultations

@router.post("/consultations", response_model=ConsultationResponse)     ##医生写诊断结果相当于创建诊断表
def create_new_consultation(consultation: ConsultationCreate, 
                          db: Session = Depends(get_db),
                          user=Depends(require_user(UserType.ADMIN, UserType.DOCTOR))):
    try:
        db_consultation = create_consultation(db, consultation)
        return db_consultation
    except HTTPException as e:
        db.rollback()
        raise e
    except Exception as e:
        db.rollback()
        import traceback
        print("异常回溯:\n", traceback.format_exc())
        raise HTTPException(
            status_code=500, 
            detail=f"创建诊断记录失败: {str(e)}"
        )

@router.get("/consultations/{consultation_id}", response_model=ConsultationResponse)
def read_consultation(consultation_id: int, db: Session = Depends(get_db),
                     user=Depends(require_user(UserType.ADMIN, UserType.DOCTOR, UserType.PATIENT,UserType.PHARMACIST))):        #患者可以通过表ID查看该次的检查，药剂师也可以查看来开药
    return get_consultation(db, consultation_id)

@router.put("/consultations/{consultation_id}", response_model=ConsultationResponse)
def update_existing_consultation(consultation_id: int, consultation: ConsultationUpdate,
                               db: Session = Depends(get_db),
                               user=Depends(require_user(UserType.ADMIN,UserType.DOCTOR))):
    return update_consultation(db, consultation_id, consultation)

@router.delete("/consultations/{consultation_id}")
def delete_existing_consultation(consultation_id: int, db: Session = Depends(get_db),
                               user=Depends(require_user(UserType.ADMIN,UserType.DOCTOR))):
    return delete_consultation(db, consultation_id)

@router.get("/consultations/patient/{patient_id}", response_model=list[ConsultationResponse])
def read_patient_consultations(
    patient_id: int, 
    db: Session = Depends(get_db),
    payload: dict = Depends(require_user(UserType.ADMIN, UserType.DOCTOR, UserType.PATIENT))
):
    # 从payload中获取用户类型和ID
    user_type = UserType.from_str(payload.get("user_type"))
    user_ref_id = int(payload.get("user_ref_id"))
    
    # 如果是患者，只能查看自己的记录
    if user_type == UserType.PATIENT and user_ref_id != patient_id:
        raise HTTPException(
            status_code=403, 
            detail="Patients can only view their own records"
        )
    
    return get_consultations_by_patient(db, patient_id=patient_id)

@router.get("/consultations/doctor/{doctor_id}", response_model=list[ConsultationResponse])
def read_doctor_consultations(
        doctor_id: int,
        db: Session = Depends(get_db),
        payload: dict = Depends(require_user(UserType.ADMIN, UserType.DOCTOR))):
    user_type = UserType.from_str(payload.get("user_type"))
    user_ref_id = int(payload.get("user_ref_id"))

    if user_type == UserType.PATIENT and user_ref_id != doctor_id:
        raise HTTPException(
            status_code=403,
            detail="Patients can only view their own records"
        )

    return get_consultations_by_doctor(db, doctor_id=doctor_id)